"""系统路由模块"""
from flask import Blueprint, jsonify, make_response
from app.utils.decorators import login_required
from app.database import get_db_connection

bp = Blueprint('system', __name__, url_prefix='/api')

@bp.route('/system/stats', methods=['GET'])
@login_required
def get_system_stats():
    """获取系统统计信息"""
    connection = None
    cursor = None
    
    try:
        connection = get_db_connection()
        cursor = connection.cursor()
        
        cursor.execute("SELECT COUNT(*) as total_products FROM products")
        total_products = cursor.fetchone()['total_products']
        
        cursor.execute("SELECT COUNT(*) as warning_products FROM products WHERE stock < 10")
        warning_products = cursor.fetchone()['warning_products']
        
        cursor.execute("SELECT COUNT(*) as out_of_stock FROM products WHERE stock = 0")
        out_of_stock = cursor.fetchone()['out_of_stock']
        
        cursor.execute("SELECT COUNT(*) as today_transactions FROM transactions WHERE DATE(transaction_time) = CURDATE()")
        today_transactions = cursor.fetchone()['today_transactions']
        
        cursor.execute("SELECT SUM(total_amount) as today_transaction_amount FROM transactions WHERE DATE(transaction_time) = CURDATE()")
        today_transaction_amount = cursor.fetchone()['today_transaction_amount'] or 0.00
        
        return jsonify({
            'success': True,
            'total_products': total_products,
            'warning_products': warning_products,
            'out_of_stock': out_of_stock,
            'today_transactions': today_transactions,
            'today_transaction_amount': round(today_transaction_amount, 2)
        })
    except Exception as e:
        return jsonify({'success': False, 'message': f'数据库操作失败: {str(e)}'}), 500
    finally:
        if cursor:
            cursor.close()
        if connection:
            connection.close()

@bp.route('/@vite/client')
def vite_client():
    """处理Vite客户端请求"""
    response = make_response('', 204)
    response.headers['Content-Type'] = 'application/javascript'
    return response

@bp.route('/@vite/<path:path>')
def handle_vite_assets(path):
    """处理Vite资源请求"""
    return jsonify({'success': False, 'message': 'Vite assets not available'}), 404

@bp.route('/static/js/<path:filename>.map')
def handle_js_sourcemap(filename):
    """处理JS source map文件请求（返回空响应，避免404日志）"""
    response = make_response('', 204)
    response.headers['Content-Type'] = 'application/json'
    return response

@bp.route('/static/css/<path:filename>.map')
def handle_css_sourcemap(filename):
    """处理CSS source map文件请求（返回空响应，避免404日志）"""
    response = make_response('', 204)
    response.headers['Content-Type'] = 'application/json'
    return response

